/*
 * @(#)AuditEventReceiverProducer.java
 * Date 2013-11-05
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.atna.inject;

import javax.enterprise.context.ApplicationScoped;

import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;

import javax.inject.Inject;

import com.nesscomputing.syslog4j.util.SyslogUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import us.hornerscorners.lamppost.atna.receiver.AuditEventSslTcpReceiver;
import us.hornerscorners.lamppost.atna.receiver.AuditEventTcpReceiver;
import us.hornerscorners.lamppost.atna.receiver.AuditEventUdpReceiver;
import us.hornerscorners.lamppost.atna.receiver.IAuditEventReceiver;

import us.hornerscorners.lamppost.ihecommon.config.AtnaConfig;
import us.hornerscorners.lamppost.ihecommon.config.IHEConfig;


/**
 * Class description
 *
 *
 * @version        v1.0, 2013-11-05
 * @author         Jim Horner
 */
public class AuditEventReceiverProducer {

    /** Field description */
    @Inject
    private IHEConfig config;

    /** Field description */
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Method description
     *
     *
     * @param receiver
     */
    public void disposes(@Disposes IAuditEventReceiver receiver) {

        try {

            logger.info("In shut-down hook...");

            if (receiver.isStarted()) {

                receiver.shutdown();
                SyslogUtility.sleep(300);
            }

        } catch (Exception e) {

            logger.error("Unable to shutdown server.", e);
        }
    }

    /**
     * Method description
     *
     *
     * @return
     */
    @Produces
    @ApplicationScoped
    public IAuditEventReceiver produces() {

        IAuditEventReceiver result = null;

        AtnaConfig atnaConfig = this.config.getAtnaConfig();

        switch (atnaConfig.getProtocol()) {

            case ssltcp :
                result = new AuditEventSslTcpReceiver(atnaConfig);

                break;

            case tcp :
                result = new AuditEventTcpReceiver(atnaConfig);

                break;

            case udp :
                result = new AuditEventUdpReceiver(atnaConfig);

                break;

            default :
                throw new IllegalArgumentException(
                    "Unrecognized ATNA protocol in config.");
        }

        if (result != null) {

            result.initialize();
        }

        return result;
    }
}
